package com.yhj.filter;

import com.alibaba.druid.util.StringUtils;
import com.yhj.model.JWTUtil;
import com.yhj.model.SecurityUser;
import com.yhj.model.User;
import com.yhj.model.UserRole;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Objects;

/**
 * @author yaohj
 * @date 2024年12月11日 11:25
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private JWTUtil jwtUtil;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            //token为空的话, 就不管它, 让SpringSecurity中的其他过滤器处理请求
            //请求放行
            filterChain.doFilter(request, response);
            return;
        }


        User oldUser = (User) redisTemplate.opsForHash().get("sys:user", token);
        if (Objects.isNull(oldUser)) {
            //该token对应用户为空的话, 就不管它, 让SpringSecurity中的其他过滤器处理请求
            //请求放行
            filterChain.doFilter(request, response);
            return;
        }

        //获取redis token，并且更新jwt token
        //校验token是否失效，自动续期
        String newToken = jwtUtil.refreshToken(token, oldUser);
        if(StringUtils.isEmpty(newToken)){
            throw new RuntimeException("illegal request，token is expired!");
        }

        //token不为空时, 解析token
        User user = null;
        try {
            user = jwtUtil.parseToken(newToken);
        } catch (Exception e) {
            // 过滤器中抛出的异常，无法被统一异常捕获，所以在这里直接返回

            return;
        }

        UserRole userRole= new UserRole();
        userRole.setId(1);
        userRole.setUserId(user.getId());
        userRole.setRoleId(1);
        userRole.setRoleName("ADMIN");
        UserRole userRole2= new UserRole();
        userRole2.setId(2);
        userRole2.setUserId(user.getId());
        userRole2.setRoleId(2);
        userRole2.setRoleName("USER");
        user.setUserRoles(Collections.singletonList(userRole));
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUser(user);
        //将用户安全信息存入SecurityContextHolder, 在之后SpringSecurity的过滤器就不会拦截
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        response.setHeader("Authorization",  newToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
